package com.bestcem.xm.label.controller.v3;

import cn.hutool.core.bean.BeanUtil;
import com.bestcem.xm.common.core.constant.RegTypes;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.uitls.GRpcUtil;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.label.controller.v3.param.CreateLabelGroupRequest;
import com.bestcem.xm.label.controller.v3.param.UpdateLabelGroupNameRequest;
import com.bestcem.xm.label.controller.v3.vo.labelgroup.CreateLabelGroupVO;
import com.bestcem.xm.label.controller.v3.vo.labelgroup.DeleteLabelGroupVO;
import com.bestcem.xm.label.controller.v3.vo.labelgroup.UpdateLabelGroupVO;
import com.bestcem.xm.label.controller.vo.LabelInfoVO;
import com.bestcem.xm.label.grpc.service.param.label.ListLabelsParam;
import com.bestcem.xm.label.grpc.service.param.labelgroup.CreateLabelGroupParam;
import com.bestcem.xm.label.grpc.service.param.labelgroup.UpdateLabelGroupNameParam;
import com.bestcem.xm.label.service.LabelGroupService;
import com.bestcem.xm.label.service.dto.LabelGroupDTO;
import com.bestcem.xm.label.service.dto.label.LabelDTO;
import com.bestcem.xm.label.service.dto.label.LabelInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 标签组
 *
 * @author zh.zhang <zh.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2021-08-18
 */
@Slf4j
@RestController
@RequestMapping("/member/ind/v3")
public class IndividualLabelGroupController {

    @Autowired
    private LabelGroupService labelGroupService;

    /**
     * 获取标签信息
     *
     * @param includeValue
     * @return
     */
    @GetMapping(value = "/label_group")
    public XmResultJson getLabelGroup(@RequestParam("include_value") boolean includeValue,
                                      HttpServletRequest httpServletRequest) {
        
        String orgId = SecurityContextHolder.getOrgId();
        ListLabelsParam param = new ListLabelsParam();
        param.setOrgId(orgId);
        param.setAttribute(0);
        param.setIncludeValue(includeValue);
        List<LabelInfoDTO> labelInfoDTOS = labelGroupService.listLabels(param);

        // 处理返回结果
        if (CollectionUtils.isEmpty(labelInfoDTOS)) {
            labelInfoDTOS = Collections.emptyList();
        }
        List<LabelInfoVO> labelInfoVOs = labelInfoDTOS.stream().map(info -> {
            LabelInfoVO vo = new LabelInfoVO();
            BeanUtil.copyProperties(info, vo);
            return vo;
        }).collect(Collectors.toList());
        return XmResultJson.success(labelInfoVOs);
    }

    /**
     * 新建标签组
     *
     * @param request CreateLabelGroupRequest
     * @return XmResultJson
     * @author zh.zhang <zh.zhang@idiaoyan.com>
     * @date 2021-08-18
     */
    @PostMapping("/label_group")
    public XmResultJson createLabelGroup(@Valid @RequestBody CreateLabelGroupRequest request,
                                             HttpServletRequest httpServletRequest) {
        
        String orgId = SecurityContextHolder.getOrgId();
        request.setOrgId(orgId);
        request.setAttribute(0);
        CreateLabelGroupParam createlabelGroupParam = this.convert(request);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(createlabelGroupParam);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(-1, violation.getMessage());
        }

        ServiceResult<LabelGroupDTO> result = labelGroupService.createLabelGroup(createlabelGroupParam);
        if (result.isSuccess()) {
            CreateLabelGroupVO createLabelGroupVO = new CreateLabelGroupVO();
            createLabelGroupVO.setGroupId(result.getData().getId());
            return XmResultJson.success(createLabelGroupVO);
        } else {
            return XmResultJson.fail(-1, result.getMsg());
        }
    }

    /**
     * 更新标签组名称
     *
     * @param id 标签组id
     * @param request UpdateLabelGroupNameRequest
     * @return XmResultJson
     * @author zh.zhang <zh.zhang@idiaoyan.com>
     * @date 2021-08-18
     */
    @PutMapping("/label_group/{id}")
    public XmResultJson updateLabelGroup(@PathVariable String id,
                                             @Valid @RequestBody UpdateLabelGroupNameRequest request,
                                             HttpServletRequest httpServletRequest) {
        
        String orgId = SecurityContextHolder.getOrgId();
        request.setOrgId(orgId);
        request.setLabelGroupId(id);
        UpdateLabelGroupNameParam updateLabelGroupNameParam = this.convert(request);

        // 参数校验
        Set<ConstraintViolation<Object>> violations = GRpcUtil.validateParam(updateLabelGroupNameParam);
        if (!CollectionUtils.isEmpty(violations)) {
            ConstraintViolation<Object> violation = violations.iterator().next();
            return XmResultJson.fail(-1, violation.getMessage());
        }

        ServiceResult<String> result = labelGroupService.updateLabelGroup(updateLabelGroupNameParam);
        if (result.isSuccess()) {
            UpdateLabelGroupVO updateLabelGroupVO = new UpdateLabelGroupVO();
            updateLabelGroupVO.setGroupId(result.getData());
            return XmResultJson.success(updateLabelGroupVO);
        } else {
            return XmResultJson.fail(-1, result.getMsg());
        }
    }

    /**
     * 通过标签组ID删除标签组、标签、标签值、
     *
     * @param id 标签组id
     * @return XmResultJson
     * @author zh.zhang <zh.zhang@idiaoyan.com>
     * @date 2021-08-18
     */
    @DeleteMapping("/label_group/{id}")
    public XmResultJson deleteLabelGroup(@PathVariable String id) {
        // 校验参数
        if (!Pattern.matches(RegTypes.OBJECT_ID, id)) {
            String msg = String.format("标签组ID：%s 格式异常！", id);
            return XmResultJson.fail(-1, msg);
        }

        ServiceResult<LabelGroupDTO> result = labelGroupService.deleteLabelGroup(id);
        if (result.isSuccess()) {
            List<String> labelIds = result.getData().getLabelDTOS().stream().map(LabelDTO::getId)
                .collect(Collectors.toList());
            DeleteLabelGroupVO deleteLabelGroupVO = new DeleteLabelGroupVO();
            deleteLabelGroupVO.setLabelIds(labelIds);
            return XmResultJson.success(deleteLabelGroupVO);
        } else {
            return XmResultJson.fail(-1, result.getMsg());
        }
    }

    /**
     * CreateLabelGroupRequest -> CreateLabelGroupParam
     *
     * @param request HttpCreateLabelGroupParam
     * @return CreateLabelGroupParam
     */
    private CreateLabelGroupParam convert(CreateLabelGroupRequest request) {
        CreateLabelGroupParam createParam = new CreateLabelGroupParam();
        createParam.setOrgId(request.getOrgId());
        createParam.setName(request.getName());
        createParam.setSerial(request.getSerial());
        createParam.setAttribute(request.getAttribute());

        return createParam;
    }

    /**
     * UpdateLabelGroupNameRequest -> UpdateLabelGroupNameParam
     *
     * @param request HttpUpdateLabelGroupNameParam
     * @return UpdateLabelGroupNameParam
     */
    private UpdateLabelGroupNameParam convert(UpdateLabelGroupNameRequest request) {
        UpdateLabelGroupNameParam updateParam = new UpdateLabelGroupNameParam();
        updateParam.setOrgId(request.getOrgId());
        updateParam.setLabelGroupId(request.getLabelGroupId());
        updateParam.setName(request.getName());
        return updateParam;
    }
}
